<template>
	<view>
		<view class="scan size">
		    <view class="sectionview"><view id="qr-reader" style="width:100%;height:100%;"></view></view>
		</view>
	</view>
</template>
<script>

export default {
    data() {
        return {
            cameraId: '',
        };
    },
    mounted() {
        this.init();
    },
    beforeDestroy() {
        this.stop();
    },
    methods: {
        init() {
			this.AddJs('https://blog.minhazav.dev/assets/research/html5qrcode/html5-qrcode.min.js');
            //需要加载时间建议延时一点再获取设备列表
            setTimeout(() => {
                this.getCameras();
            }, 1000);
        },
		AddJs(url) {
			//console.log( 'url：',url);
			return new Promise((resolve, reject) => {
				const script = document.createElement('script');
				script.src = url;
				script.type = 'text/javascript';
				document.body.appendChild(script);
				script.onload = () => {
					resolve();
				};
			});
		},
		
		
        stop() {
            this.html5QrCode
                .stop()
                .then(ignore => {
                    // QR Code scanning is stopped.
                    console.log('QR Code scanning stopped.');
                })
                .catch(err => {
                    // Stop failed, handle it.
                    console.log('Unable to stop scanning.');
                });
        },
        start() {
            this.html5QrCode = new Html5Qrcode('qr-reader');
            this.html5QrCode
                .start(
					this.cameraId, // retreived in the previous step.
                    {fps: 10,  qrbox: 250 },
                    qrCodeMessage => {
                        if (qrCodeMessage) {
							
							let pages = getCurrentPages(); // 获取当前页面栈的实例
							let prevPage = pages[pages.length - 2]; //上一页页面实例
							prevPage.$vm.otherFun({sn:qrCodeMessage})//给上一个页面绑定方法，传递object
							uni.navigateBack();

                            this.stop();
                        }
                    },
                    errorMessage => {
                    }
                )
                .catch(err => {
                    console.log(`Unable to start scanning, error: ${err}`);
					this.$modal.msgError("扫码失败")
                });
        },
        getCameras() {
            Html5Qrcode.getCameras()
                .then(devices => {
                    /**
                     * devices:[{ id: "id", label: "label" }]
                     */
                    if (devices && devices.length) {
						if (devices.length > 1) {
							this.cameraId = devices[devices.length-1].id;
						} else {
							this.cameraId = devices[0].id;
						}
						this.start();
                    }
                })
                .catch(err => {
					this.$modal.msgError("启用相机失败")
                });
        }
    }
};
</script>
<style>
.scan {
    width: 100%;
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
}
</style>